<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable @keyup.enter.native="handleQuery">
          <el-option label="规格" :value="1" />
          <el-option label="验机" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
	    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['option:option:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="optionList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      border
    >
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="机型" align="center" prop="modelTypes">
        <template v-slot="scope">
          <div>
            {{modelTypeString(scope.row)}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作系统" align="center" prop="systemType">
        <template v-slot="scope">
          {{systemTypeString(scope.row)}}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <el-switch
            v-model="scope.row.status"
            active-text="启用"
            inactive-text="关闭"
            :active-value="1"
            :inactive-value="0"
            @change="switchStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type" width="100">
        <template v-slot="scope">
          <el-tag v-if="scope.row.type === 1">规格</el-tag>
          <el-tag v-if="scope.row.type === 2" type="warning">验机</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" width="80" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['option:option:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.parentId === 0"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['option:option:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['option:option:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改验机选项对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父id" prop="parentId">
          <treeselect v-model="form.parentId" :options="optionOptions" :normalizer="normalizer" placeholder="请选择上级"  />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="机型" prop="modelTypes">
          <el-select v-model="form.modelTypes" placeholder="请选择机型" multiple>
            <el-option
              v-for="dict in dict.type.model_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作系统" prop="systemType">
          <el-select v-model="form.systemType" placeholder="请选择操作系统" multiple>
            <el-option
              v-for="dict in dict.type.operating_system"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type" v-if="!form.parentId || form.parentId === 0">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">规格</el-radio>
            <el-radio :label="2">验机</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOption, getOption, delOption, addOption, updateOption } from "@/api/comment/option";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Option",
  dicts: ['model_type', 'operating_system'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 验机选项表格数据
      optionList: [],
      // 验机选项树选项
      optionOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        parentId: null,
        name: null,
        modelTypes: null,
        systemType: null,
        status: null,
        type: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    switchStatusChange(row) {
      updateOption(row).then(res => {
        this.$modal.msgSuccess("修改成功");
      })
    },
    //系统
    systemTypeString(row) {
      if(!row.systemType)
        return "所有";
      const arr = this.dict.type.operating_system;
      let res = "";
      let list = row.systemType.split(",");
      list.forEach(it => {
        for(let i = 0; i < arr.length; i++) {
          if(it === arr[i].value)
            res += arr[i].label + "-";
        }
      })
      return res.substring(0, res.length - 1);
    },
    modelTypeString(row) {
      if(!row.modelTypes)
        return "所有";
      const arr = this.dict.type.model_type;
      let res = "";
      let list = row.modelTypes.split(",");
      list.forEach(it => {
        for(let i = 0; i < arr.length; i++) {
          if(it === arr[i].value)
            res += arr[i].label + "-";
        }
      })
      return res.substring(0, res.length - 1);
    },
    /** 查询验机选项列表 */
    getList() {
      this.loading = true;
      listOption(this.queryParams).then(response => {
        this.optionList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 转换验机选项数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
	/** 查询验机选项下拉树结构 */
    getTreeselect() {
      listOption().then(response => {
        this.optionOptions = [];
        const data = { id: 0, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.optionOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        name: null,
        modelTypes: null,
        systemType: null,
        status: null,
        delFlag: null,
        type: null,
        sort: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加验机选项";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.id;
      }
      getOption(row.id).then(response => {
        this.form = response.data;
        if(this.form.modelTypes)
          this.form.modelTypes = this.form.modelTypes.split(",");
        if(this.form.systemType)
          this.form.systemType = this.form.systemType.split(",");
        this.open = true;
        this.title = "修改验机选项";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if(this.form.modelTypes)
          this.form.modelTypes = this.form.modelTypes.toString();
        if(this.form.systemType)
          this.form.systemType = this.form.systemType.toString();
        if (valid) {
          if (this.form.id != null) {
            updateOption(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              if(this.form.modelTypes)
                this.form.modelTypes = this.form.modelTypes.split(",");
              if(this.form.systemType)
                this.form.systemType = this.form.systemType.split(",");
            });
          } else {
            addOption(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              if(this.form.modelTypes)
                this.form.modelTypes = this.form.modelTypes.split(",");
              if(this.form.systemType)
                this.form.systemType = this.form.systemType.split(",");
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除验机选项编号为"' + row.id + '"的数据项？').then(function() {
        return delOption(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
